package com.artifex.mupdf.viewer

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters

@Database(
    entities = [Book::class, ],
    version = 2,
    exportSchema = false
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {

    // Migration from version 1 to 2
//    val MIGRATION_1_2 = object : Migration(1, 2) {
//        override fun migrate(database: SupportSQLiteDatabase) {
//            // Add bookmarks table
//            database.execSQL(
//                "CREATE TABLE IF NOT EXISTS bookmarks (" +
//                        "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
//                        "bookId TEXT NOT NULL, " +
//                        "pageNumber INTEGER NOT NULL, " +
//                        "note TEXT, " +
//                        "createdDate INTEGER NOT NULL, " +
//                        "FOREIGN KEY(bookId) REFERENCES books(id) ON DELETE CASCADE)"
//            )
//
//            // Add index for better performance
//            database.execSQL("CREATE INDEX index_bookmarks_bookId ON bookmarks(bookId)")
//        }
//    }

    abstract fun bookDao(): BookDao

    companion object {
        private const val DATABASE_NAME = "book_reader_database"

        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = buildDatabase(context)
                INSTANCE = instance
                instance
            }
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java,
                DATABASE_NAME
            )
                .addCallback(DatabaseCallback())
//                .addMigrations(MIGRATION_1_2)
                .setJournalMode(JournalMode.TRUNCATE)
                .build()
        }
    }
}